package com.hmall.search.listener;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.hmall.search.domain.po.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class ItemSyncListener {

    @Autowired
    private ElasticsearchClient esClient;

    /**
     * 监听保存商品队列
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("item.save.sync.queue"),
            exchange = @Exchange(value = "item.sync.exchange", type = ExchangeTypes.DIRECT),
            key = "item.save.sync"
    ))
    public void listenItemSaveSync(ItemDoc doc) throws IOException {
        esClient.index(builder -> builder.index("items").id(doc.getId()).document(doc));
        log.info("保存商品文档，doc={}", doc);
    }

    /**
     * 监听商品删除队列
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("item.remove.sync.queue"),
            exchange = @Exchange(value = "item.sync.exchange", type = ExchangeTypes.DIRECT),
            key = "item.remove.sync"
    ))
    public void listenItemRemoveSync(Long itemId) throws IOException {
        esClient.delete(builder->builder.index("items").id(itemId.toString()));
        log.info("删除商品文档，id={}", itemId);
    }
}